<template>
  <div class="main user-layout-login">
    <!-- 输入框 -->
    <a-tabs
        :activeKey="customActiveKey"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
        size="large"
    >
      <a-tab-pane
          key="tab1"
          tab="账号密码登录"
          class="tab-pane"
      >
        <a-form-model
            ref="form1"
            :model="form1"
            :rules="rules1"
            class="form-model"
        >
          <a-form-model-item prop="account">
            <a-input
                size="large"
                type="text"
                placeholder="邮箱/手机号"
                v-model="form1.account"
            >
              <a-icon
                  slot="prefix"
                  type="user"
                  :style="{ color: 'rgba(0,0,0,.25)' }"
              />
            </a-input>
          </a-form-model-item>

          <a-form-model-item prop="password">
            <a-input-password
                size="large"
                placeholder="密码"
                v-model="form1.password"
                @keydown.enter="handleSubmit1"
            >
              <a-icon
                  slot="prefix"
                  type="lock"
                  :style="{ color: 'rgba(0,0,0,.25)' }"
              />
            </a-input-password>
          </a-form-model-item> <!-- 登录按钮 -->
          <a-form-model-item style="margin-top:40px">
            <a-button
                size="large"
                type="primary"
                htmlType="submit"
                class="login-button"
                :loading="state.loginBtn"
                :disabled="state.loginBtn"
                @click="handleSubmit1"
            >登录
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-tab-pane>

      <a-tab-pane
          key="tab2"
          tab="手机验证码"
          class="tab-pane"
      >
        <a-form-model
            ref="form2"
            :model="form2"
            :rules="rules2"
            class="form-model"
        >
          <a-form-model-item prop="account">
            <a-input-group compact>
              <NationCodeSelect
                  v-model="form2.mobileAreaCode"
                  style="width: 24%;height:40px"
              />
              <a-input
                  v-model="form2.account"
                  style="width: 76%;height:40px"
              />
            </a-input-group>
          </a-form-model-item>
          <a-form-model-item prop="kaptcha">
            <div class="code-img-box">
              <a-input
                  size="large"
                  type="text"
                  placeholder="图形验证码"
                  v-model="form2.kaptcha"
              >
                <a-icon
                    slot="prefix"
                    type="user"
                    :style="{ color: 'rgba(0,0,0,.25)' }"
                />
              </a-input>
              <div
                  class="code-img"
                  @click="getFn"
              >
                <img
                    :src="kaptcha.image"
                    alt="图形验证码"
                >
              </div>
            </div>
          </a-form-model-item>
          <a-form-model-item prop="verifyCode">
            <div class="flex-justify-between ">
              <a-input
                  style="width: 60%"
                  size="large"
                  placeholder="验证码"
                  v-model="form2.verifyCode"
              >
                <a-icon
                    slot="prefix"
                    type="safety"
                    :style="{ color: 'rgba(0,0,0,.25)' }"
                />
              </a-input>
              <a-button
                  style="width: 30%"
                  size="large"
                  type="primary"
                  htmlType="submit"
                  :loading="state.codeloading"
                  :disabled="state.code"
                  @click="sendVerifyCodeFn"
              >{{ state.codemsg }}
              </a-button>
            </div>
          </a-form-model-item> <!-- 登录按钮 -->
          <a-form-model-item style="margin-top:40px">
            <a-button
                size="large"
                type="primary"
                htmlType="submit"
                class="login-button"
                :loading="state.loginBtn"
                :disabled="state.loginBtn"
                @click="handleSubmit2"
            >登录
            </a-button>
          </a-form-model-item>
        </a-form-model>
        <p class="protocol">
          注册即代表同意 <span class="text-button" @click.stop="$refs.ProtocolModal.open()">隐私条款</span>
        </p>
      </a-tab-pane>
    </a-tabs>
    <!-- <div><span
        class="text-button"
        @click="$nav('/user/resetpwd')"
      >忘记密码</span></div> -->
    <!-- 人机验证 -->
    <two-step-captcha
        v-if="requiredTwoStepCaptcha"
        :visible="stepCaptchaVisible"
        @success="stepCaptchaSuccess"
        @cancel="stepCaptchaCancel"
    ></two-step-captcha>
  </div>
</template>

<script>
import md5 from "md5";
import {mapActions, mapState} from "vuex";

import {timeFix} from "@/utils/util";
import {verifyCode} from "@/api/login";

import {ACCESS_TOKEN, USER_ID, USER_INFO} from "@/store/mutation-types";
import storage from "store";

import NationCodeSelect from "@/components/Select/nationCodeSelect";

import {sendVerifyCode} from "@/api/sms";
import {get} from "@/api/kaptcha";


export default {
  components: {
    NationCodeSelect,
  },
  data() {
    return {
      customActiveKey: "tab1",
      loginBtn: false,
      // login type: 0 email, 1 account, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 account, 2 telephone
        loginType: 0,
        smsSendBtn: false,

        codeloading: false, //验证码loadding
        code: false, //验证码按钮禁用
        codemsg: "获取验证码",
        timeId: "",
      },

      form1: {
        account: "", //账号
        password: "", //	密码，md5加密
      },
      rules1: {
        account: [
          {
            required: true,
            message: "请输入账号",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
      },

      kaptchaLoadding: false, //图形验证码loadding
      kaptcha: {},
      // 图形验证码信息
      form2: {
        account: "", //账号
        password: "", //	密码，md5加密
        verifyCode: "", //手机验证密码
        mobileAreaCode: "+86",

        kaptcha: "", //图形验证码
      },
      rules2: {
        account: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        verifyCode: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
        kaptcha: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {

  },
  computed: {
    ...mapState({
      // 动态主路由
      mainMenu: (state) => state.asyncRouter.addRouters,
    }),
  },
  methods: {
    ...mapActions(["Login", "Logout"]),
    // 切换登录tab
    handleTabClick(key) {
      this.customActiveKey = key;
      if(this.customActiveKey=='tab2'){
        this.getFn();
      }
      if (this.$refs.form1 !== undefined) {
        this.$refs.form1.resetFields();
      }
      if (this.$refs.form2 !== undefined) {
        this.$refs.form2.resetFields();
      }
    },
    // 登录
    handleSubmit1() {
      this.$refs.form1.validate(async (valid) => {
        if (valid) {
          const loginParams = {...this.form1};
          loginParams.password = md5(this.form1.password);
          this.login(loginParams);
        } else {
          return false;
        }
      });
    },
    // 登录
    async login(params) {
      this.state.loginBtn = true;
      let res = await this.Login(params);
      if (res.code == 0) {
        if (res.data.menuList && res.data.menuList.length < 1) {
          this.$notification.warning({
            message: "提示",
            description: `账号暂无权限，请联系管理员`,
          });
          storage.remove(ACCESS_TOKEN);
          storage.remove(USER_INFO);
        } else {
          this.loginSuccess(res);
        }
      }
      this.state.loginBtn = false;
    },

    // 登录成功
    loginSuccess(res) {
      this.$storage.set( ACCESS_TOKEN, res.data.tokenId, );
      this.$storage.set(USER_INFO, res.data,);
      this.$storage.set(USER_ID, res.data.id,);
      this.$router.push({path: "/"}).catch((err) => {
        console.log(err)
      });
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: "欢迎",
          description: `${timeFix()}，欢迎回来`,
        });
      }, 1000);
    },

    // 获取手机验证码
    async sendVerifyCodeFn() {
      if (this.form2.mobileAreaCode == "") {
        return false;
      }
      if (this.form2.account == "") {
        return false;
      }
      if (this.form2.kaptcha == "") {
        return false;
      }
      this.state.codeloading = true;
      let res = await sendVerifyCode({
        mobileAreaCode: this.form2.mobileAreaCode,
        mobile: this.form2.account,
        type: 1,
        imgCode: this.form2.kaptcha,
        imgId: this.kaptcha.id,
      });
      if (res.code == 0) {
        this.state.code = true;
        this.$message.success("短信发送成功");
        this.setTimeoutFn();
      } else if (res.code == "100042") {
        this.getFn();
      }
      this.state.codeloading = false;
    },
    // 获取图形验证码
    async getFn() {
      this.kaptchaLoadding = true;
      let res = await get();
      if (res.code == 0) {
        this.kaptcha = res.data;
        this.kaptchaLoadding = false;
      }
    },
    // 登录
    handleSubmit2() {
      this.$refs.form2.validate(async (valid) => {
        if (valid) {
          this.verifyCodeFn();
        } else {
          return false;
        }
      });
    },
    // 验证码登录
    async verifyCodeFn() {
      this.state.loginBtn = true;
      let res = await verifyCode({
        account: this.form2.account,
        verifyCode: this.form2.verifyCode,
        mobileAreaCode: this.form2.mobileAreaCode,
      });
      if (res.code === 0) {
        this.loginSuccess(res);
      }
      this.state.loginBtn = false;
    },

    // 倒计时
    setTimeoutFn() {
      let time = this.state.time;
      this.state.timeId = setInterval(() => {
        this.state.codemsg = `${time--}秒后重试`;
        if (time < 1) {
          this.state.codemsg = "获取验证码";
          this.state.code = false;
          clearInterval(this.state.timeId);
        }
      }, 1000);
    },
  },
  beforeDestroy() {
    clearInterval(this.state.timeId);
  },
};
</script>

<style lang="less" scoped>
.user-layout-login {
  // padding-top: 20px;
  label {
    font-size: 14px;
  }

  .form-model {
    margin-top: 20px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 46px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }

  .code-img-box {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .code-img {
      width: 200px;
      height: 40px;
      margin-left: 50px;
      border-radius: 4px;
      // border: 1px solid #eee;
      cursor: pointer;

      img {
        width: 100%;
        height: 40px;
        border-radius: 4px;
      }
    }
  }

  .protocol {
    text-align: center;
  }
}
</style>
